package router

import (
	"context"
	"github.com/aberic/gnomon/grope"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/model"
	"net/http"
)

func RouteImage(hs *grope.GHttpServe) {
	// 仓库相关路由设置
	route := hs.Group("/image")
	route.Post("/pull", imagePull) // 20200518032852 20200518033200
	route.Get("/list", imageList)
	route.Get("/remove/:id", imageRemove)
	route.Post("/tag", imageTag)
}

func imagePull(ctx *grope.Context) {
	pull := &model.ImagePull{}
	if err := ctx.ReceiveJSON(pull); nil != err {
		responseFailJSON(ctx, err)
		return
	}
	if err := client.Obtain().Image().Pull(context.Background(), pull.RefStr); nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess})
}

func imageList(ctx *grope.Context) {
	images, err := client.Obtain().Image().List(context.Background())
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: images})
}

func imageRemove(ctx *grope.Context) {
	item, err := client.Obtain().Image().Remove(context.Background(), ctx.Value("id"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: item})
}

func imageTag(ctx *grope.Context) {
	tag := &model.ImageTag{}
	if err := ctx.ReceiveJSON(tag); nil != err {
		responseFailJSON(ctx, err)
		return
	}
	err := client.Obtain().Image().Tag(context.Background(), tag.Source, tag.Target)
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess})
}
